﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Memcached.ClientLibrary;
using JXT.PrimaryKey.Batman.Cache;
using JXT.PrimaryKey.Batman.Core.Configuration;

namespace JXT.PrimaryKey.Batman.Core.Cache
{
    /// <summary>
    /// 默认的基于Memcached缓存
    /// </summary>
    public class MemcachedCache : CacheBase
    {
        private static readonly object _synLock = new object();

        private static MemcachedClient _memcachedClient;

        public static MemcachedClient MemcachedClient
        {
            get
            {
                if (_memcachedClient == null)
                {
                    lock (_synLock)
                    {
                        if (_memcachedClient == null)
                        {
                            InitMemcachedCacheClient();
                        }
                    }
                }
                return _memcachedClient;
            }
        }

        private static void InitMemcachedCacheClient()
        {
            var pool = SockIOPool.GetInstance();
            var setting = SupernovaConfigurationManager.GetServiceConfigurationSection().MemcachedSetting;
            var serverList = setting.Select(e => String.Format("{0}:{1}", e.Ip, e.Port)).ToArray();
            pool.SetServers(serverList);
            if (setting.DefaultConnections > 0)
                pool.InitConnections = setting.DefaultConnections;
            if (setting.MinConnections > 0)
                pool.MinConnections = setting.MinConnections;
            if (setting.MaxConnections > 0)
                pool.MaxConnections = setting.MaxConnections;
            if (setting.Timeout > 0)
                pool.SocketTimeout = setting.Timeout;
            pool.Initialize();
            _memcachedClient = new MemcachedClient();
            _memcachedClient.EnableCompression = true;
        }

        public override void Add(string ns, string key, object value, TimeSpan ts)
        {
            MemcachedClient.Set(key, value, DateTime.Now.Add(ts));
        }

        public override object Get(string ns, string key)
        {
            return MemcachedClient.Get(key);
        }

        public override bool Exists(string ns, string key)
        {
            return MemcachedClient.KeyExists(key);
        }

        public override void Remove(string ns, string key)
        {
            MemcachedClient.Delete(key);
        }

        public override void Clear(string ns)
        {
            //throw new NotImplementedException();
        }

        public override void Clear()
        {
            //throw new NotImplementedException();
        }
    }
}
